import {
	defineStore
} from 'pinia';
import {
	computed,
	ref
} from 'vue';
export const useCartStore = defineStore('cart', () => {
	// // 声明数据
	// const cnt = ref(0)
	// const msg = ref('hello, moxin')
	// // 声明计算属性
	// const doubledCnt = computed(() => cnt.value * 2)
	// // 声明方法
	// const modifyCnt = (nVal) => (cnt.value = nVal)
	// // 暴露所有的定义
	// 每个商品对象含有信息：{goods_id,goods_name,goods_price,goods_count,goods_small_logo,goods_state}
	// 持久化到本地
	const cartList = ref(JSON.parse(uni.getStorageSync('cartList') || '[]'))
	const saveToLocal = () => uni.setStorageSync('cartList', JSON.stringify(cartList.value))
	// 添加购物车：
	const addToCart = nGoods => {
		const findRes = cartList.value.find(ele => ele.goods_id === nGoods.goods_id)
		if (findRes) findRes.goods_count++
		else cartList.value.push(nGoods)
		saveToLocal()
	}
	// 更新状态
	const updateGoodsState = nGoods => {
		// 查找对应的对象
		const findRes = cartList.value.find(ele => ele.goods_id === nGoods.goods_id)
		if (!findRes) return console.log('没找到');
		findRes.goods_state = nGoods.goods_state
		saveToLocal()
	}
	// 更新数量
	const updateGoodsCount = nGoods => {
		// 查找对应的对象
		const findRes = cartList.value.find(ele => ele.goods_id === nGoods.goods_id)
		if (!findRes) return console.log('没找到');
		findRes.goods_count = nGoods.goods_count
		saveToLocal()
	}
	// 删除商品
	const removeGoods = targetId => {
		cartList.value = cartList.value.filter(ele => ele.goods_id !== targetId)
		saveToLocal()
	}
	// 购物车总数
	const totalCnt = computed(() => cartList.value.reduce((prev, cur) => (prev + cur.goods_count), 0))
	// 购物车选中总数
	const totalCheckedCnt = computed(() => cartList.value.reduce((prev, cur) => (prev + (cur.goods_state ? cur
		.goods_count : 0)), 0))
	// 购物车是否全选
	const isAllChecked = computed(() => totalCnt.value === totalCheckedCnt.value)
	// 修改所有购物车的选中状态：
	const updateAllGoodsState = nState => {
		cartList.value.forEach(ele => ele.goods_state = nState)
		saveToLocal()
	}
	// 已选商品的总价格
	const totalCheckedPrice = computed(() => cartList.value.reduce((prev, cur) => (prev + (cur.goods_state ? cur
		.goods_count * cur.goods_price : 0)), 0).toFixed(2))
	return {
		cartList,
		addToCart,
		totalCnt,
		updateGoodsState,
		updateGoodsCount,
		removeGoods,
		totalCheckedCnt,
		isAllChecked,
		updateAllGoodsState,
		totalCheckedPrice
	}
});